//
//  LZTOAuthViewController.swift
//  LZTWeibo
//
//  Created by Yin jianxun on 16/8/11.
//  Copyright © 2016年 YinJianxun. All rights reserved.
//

import UIKit
import SVProgressHUD

class LZTOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        
        //拼接授权 请求的url 参数包含
//        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBREDIRECT_URI)")!
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBREDIRECT_URI)") else {
            return
        }
        
        //webview的代理
        webView.delegate = self
        
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
    }
    
    //实现按钮点击事件
    //取消
    @objc private func cancelClick() {
        dismissViewControllerAnimated(false, completion: nil)
    }
    //自动填充
    @objc private func autoFillClick() {
        
        //拼接 js用的字符串
        let jsString = "document.getElementById('userId').value='\(WBNAME)',document.getElementById('passwd').value='\(WBPassWd)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
    }
    
    private func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LZTOAuthViewController.cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LZTOAuthViewController.autoFillClick))
        navigationItem.title = "微博登录"
        
    }
 
    //懒加载 webView
    private lazy var webView: UIWebView = UIWebView()
}

extension LZTOAuthViewController: UIWebViewDelegate {
    
    // 监听 webView将要加载的request
    // 如果不实现，默认返回 true
    // 返回false的时候，停止加载request、
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBREDIRECT_URI) {
            
            //拿到 请求参数 。URL中？后面的部分
            // 判断是否为nil，因为为可选值，就有可能为nil
            if let query = request.URL?.query {
                //获取 code
                let code = query.substringFromIndex("code=".endIndex)
                
                //利用userAccountViewModel 进行请求数据并判断是否请求成功
                LZTUserAccountViewModel.sharedTools.getUserAccount(code, finish: { (isSuccess) in
                    
                    if !isSuccess {
                        print("userAccount 请求失败")
                        return
                    }
                    //成功加载数据后，关闭回调用页
                    self.dismissViewControllerAnimated(false, completion: { 
                        //发送通知 切换跟控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(WBNOTIFICATION, object: "oauth")
                    })
                })
                //成功加载数据后，没有必要继续加载 回调页
                return false
            }
        }
        return true
    }
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
//        SVProgressHUD.show()
    }
    
    //完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        
//        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
}

//扩展 获取授权 token
extension LZTOAuthViewController {
    
    //网络请求 所有操作全部交给 ViewModel去操作，Vc不做请求操作，不会耗时了
    
}





